C#で作成するデスクトップアプリでホバー時に色が変化し、クリック時に震えるボタン
サンプルコード
using System;
using System.Drawing;
using System.Windows.Forms;
public class AnimatedButtonApp : Form
{
private Button animatedButton;
public AnimatedButtonApp()
{
// フォーム設定
this.Text = "アニメーションボタン";
this.Size = new Size(400, 300);
// ボタン作成
animatedButton = new Button
{
Text = "クリックしてみて!",
Size = new Size(120, 40),
Location = new Point(140, 110),
BackColor = Color.Blue,
ForeColor = Color.White
};
// ホバーイベント (色の変化)
animatedButton.MouseEnter += (s, e) => animatedButton.BackColor = Color.DarkBlue;
animatedButton.MouseLeave += (s, e) => animatedButton.BackColor = Color.Blue;
// クリックイベント (震える動き)
animatedButton.Click += (s, e) =>
{
// 震える動きを実現
var originalLocation = animatedButton.Location;
for (int i = 0; i < 5; i++)
{
animatedButton.Location = new Point(originalLocation.X - 5, originalLocation.Y);
System.Threading.Thread.Sleep(50);
animatedButton.Location = new Point(originalLocation.X + 5, originalLocation.Y);
System.Threading.Thread.Sleep(50);
}
animatedButton.Location = originalLocation; // 元の位置に戻す
};
// フォームにボタンを追加
this.Controls.Add(animatedButton);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new AnimatedButtonApp());
}
}
追加説明
-
ホバー時に色が変化:
MouseEnterとMouseLeaveイベントを使用して、ボタンの背景色を変化させます。
-
クリック時に震える動き:
Button.Locationを動的に変更し、左右に揺れるアニメーションを実現します。
-
シンプルな構造:
Windows Formsを使用して、デスクトップアプリケーションを構築します。